package boot3.ws;

import boot3.service.*;
import boot3.ws.pojo.ResultMessage;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint(value = "/chat/{param}")
@Component
public class ChatEndpoint {
    private static final Map<String,Session> onLineUsers= new ConcurrentHashMap<>();
    private String user;
    private String chatroom_id;
    private static LivechatService livechatService;
    private static StudentService studentService;
    private static TeacherService teacherService;
    private static UserService userService;
    private static ChatroomService chatroomService;
    //获取由Springboot所管理的LivechatService类
    @Autowired
    public void setLivechatService(LivechatService livechatService) {
        ChatEndpoint.livechatService = livechatService;
    }
    @Autowired
    public void setStudentService(StudentService studentService) {
        ChatEndpoint.studentService=studentService;
    }
    @Autowired
    public void setTeacherService(TeacherService teacherService) {
        ChatEndpoint.teacherService = teacherService;
    }
    @Autowired
    public void setUserService(UserService userService) {
        ChatEndpoint.userService=userService;
    }
    @Autowired
    public void setChatroomService(ChatroomService chatroomService) {
        ChatEndpoint.chatroomService = chatroomService;
    }


    //建立websocket后被调用
    @OnOpen
    public void onOpen(Session session, @PathParam("param") String param) throws IOException {
        user=param.split("_")[0];
        String chatroomIdTemp=param.split("_")[1];
        chatroom_id=chatroomIdTemp;
        //将用户添加到实时聊天室中
        //先获取当前的时间
        String start_time=getTime();
            livechatService.setLiveroomUsers(chatroomIdTemp,user,start_time);
        //更新聊天室的在线人数
        chatroomService.updateChatroom(chatroom_id);
        //将用户添加到实时聊天室中
        onLineUsers.put(user,session);
    }
    //根据聊天室的ID获取聊天室中所有用户的ID
    public List<String> getLiveRoomUsers(String chatroom_id){
       return livechatService.getLiveroomUsers(chatroom_id);
    }

    //消息组播：消息在每个聊天室中传播开
    private void broadcastAllUsers(String toChatroom_id,String message) throws IOException {
        //得到toChatroom_id中的所有用户ID
        List<String> users = getLiveRoomUsers(toChatroom_id);
        //遍历users集合将users中所对应user Session取出来并发送消息
        for(String u:users){
            Session session=onLineUsers.get(u);
            if(session!=null){
                session.getBasicRemote().sendText(message);
            }
        }
    }

    //浏览器发送消息到服务端时该方法被调用
    @OnMessage
    public void onMessage(String message) throws IOException {
        System.out.println("浏览器发送消息到服务端");
        //将消息推送给指定的聊天室
        ResultMessage msg= JSON.parseObject(message, ResultMessage.class);
        //获取指定的聊天室
        String toChatroom_id = msg.getToChatroom_id();
        //获取要发送的信息
        String toMessage = msg.getMessage();
        //根据用户的id获取用户的姓名
        String userName=userService.getUserName(user);
        msg.setSenderName(userName);
//        //获取用户的身份
//        String type = msg.getType();
//        if(type.equals("student")){
//            //根据学生的ID获取这个学生的姓名
//            Student student=studentService.getStudentById(user);
//            String name=student.getStudent_name();
//            msg.setSenderName(name);
//        }
//        if(type.equals("teacher")){
//            //根据老师的ID获取这个老师的姓名
//            Teacher teacher=teacherService.getTeacherById(user);
//            String name=teacher.getTeacher_name();
//            msg.setSenderName(name);
//        }
        //注明消息发送时间
        msg.setSendTime(getTime());
        //将Resultmessage变成String类型
        ObjectMapper mapper = new ObjectMapper();
        String messageObject=mapper.writeValueAsString(msg);
        broadcastAllUsers(toChatroom_id,messageObject);
    }

    //断开Websocket的时候使用
    @OnClose
    public void onClose(Session session) throws IOException {
        System.out.println("websock close");
        //从数据库中将已经下线的用户移除
        livechatService.deleteLiveroomUsers(user,chatroom_id);
        //更新聊天室的在线人数
        chatroomService.updateChatroom(chatroom_id);
    }

    //获取当前的时间
    private String getTime(){
        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        return dateFormat.format(calendar.getTime());
    }

    //

}
